package com.chenyaowei.order.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.chenyaowei.common.exception.ServiceException;
import com.chenyaowei.common.utils.DateUtils;
import com.chenyaowei.common.utils.SecurityUtils;
import com.chenyaowei.marketing.domain.CywCouponHistory;
import com.chenyaowei.marketing.service.ICywCouponHistoryService;
import com.chenyaowei.marketing.service.ICywCouponInfoService;
import com.chenyaowei.member.domain.CywGrowthChangeHistory;
import com.chenyaowei.member.domain.CywIntegrationChangeHistory;
import com.chenyaowei.member.domain.CywMemberStatisticsInfo;
import com.chenyaowei.member.service.ICywGrowthChangeHistoryService;
import com.chenyaowei.member.service.ICywIntegrationChangeHistoryService;
import com.chenyaowei.member.service.ICywMemberStatisticsInfoService;
import com.chenyaowei.order.domain.CywOrder;
import com.chenyaowei.order.domain.CywOrderItem;
import com.chenyaowei.order.enums.OrderStatusEnum;
import com.chenyaowei.order.mapper.CywOrderMapper;
import com.chenyaowei.order.service.ICywOrderItemService;
import com.chenyaowei.order.service.ICywOrderService;
import com.chenyaowei.order.vo.MonthTurnoverVO;
import com.chenyaowei.order.vo.StatisticsVO;
import com.chenyaowei.product.domain.CywProSkuInfo;
import com.chenyaowei.product.service.ICywProSkuInfoService;
import com.chenyaowei.ware.bo.OrderUnlockStockBo;
import com.chenyaowei.ware.service.ICywWareSkuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * 订单Service业务层处理
 *
 * @author 陈耀威
 * @date 2023-12-03
 */
@Service
public class CywOrderServiceImpl implements ICywOrderService {

    @Autowired
    private CywOrderMapper cywOrderMapper;

    @Autowired
    private ICywOrderItemService orderItemService;

    @Autowired
    private ICywWareSkuService wareSkuService;

    @Autowired
    private ICywMemberStatisticsInfoService memberStatisticsInfoService;

    @Autowired
    private ICywCouponInfoService couponInfoService;

    @Autowired
    private ICywCouponHistoryService couponHistoryService;

    @Autowired
    private ICywProSkuInfoService skuInfoService;

    @Autowired
    private ICywGrowthChangeHistoryService growthChangeHistoryService;

    @Autowired
    private ICywIntegrationChangeHistoryService integrationChangeHistoryService;

    private final Lock lock = new ReentrantLock();

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public CywOrder selectCywOrderById(Long id) {
        return cywOrderMapper.selectCywOrderById(id);
    }


    @Override
    public List<CywOrder> selectListForFront(CywOrder cywOrder) {
        cywOrder.setMemberId(SecurityUtils.getUserId());
        cywOrder.setDeleteStatus(0);
        List<CywOrder> list = cywOrderMapper.selectCywOrderList(cywOrder);
        if (CollectionUtil.isNotEmpty(list)){
            buildOrderItems(list);
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int cancelOrder(String orderSn, Integer status) {
        //1、修改订单状态
        int count = cywOrderMapper.updateOrderStatus(orderSn, status);
        if (count == 1){
            //2、解锁库存
            List<CywOrderItem> orderItems = orderItemService.selectListByOrderSn(orderSn);
            List<OrderUnlockStockBo> unlockStockBos = orderItems.stream().map(item -> {
                OrderUnlockStockBo orderUnlockStockBo = new OrderUnlockStockBo();
                BeanUtils.copyProperties(item, orderUnlockStockBo);
                return orderUnlockStockBo;
            }).collect(Collectors.toList());
            int rows = wareSkuService.unlockStock(unlockStockBos);
            if (rows == 0){
                throw new ServiceException("库存解锁失败");
            }
            System.out.println("订单号：" + orderSn + " 库存解锁成功");
            // 3、回退优惠卷
            CywOrder order = cywOrderMapper.selectOrderByOrderSn(orderSn);
            Long couponHistoryId = order.getCouponHistoryId();
            if (couponHistoryId != null){
                CywCouponHistory returnCoupon = new CywCouponHistory();
                CywCouponHistory couponHistory = couponHistoryService.selectCywCouponHistoryById(couponHistoryId);
                BeanUtils.copyProperties(couponHistory, returnCoupon);
                returnCoupon.setOrderId(null);
                returnCoupon.setOrderSn(null);
                //0-未使用；1-已使用；2-已过期
                returnCoupon.setUseStatus(couponHistory.getEndTime().before(new Date()) ? 2 : 0);
                couponHistoryService.deleteCywCouponHistoryById(couponHistory.getId());
                couponHistoryService.insertCywCouponHistory(returnCoupon);
            }
        }
        return count;
    }

    @Override
    public List<CywOrder> selectTimeOutOrderList() {
        return cywOrderMapper.selectTimeOutOrderList();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handlePayResult(String orderSn) {
        try{
            if (lock.tryLock()){
                CywOrder order = cywOrderMapper.selectOrderByOrderSn(orderSn);
                if (order.getStatus().equals(OrderStatusEnum.CREATE_NEW.getCode())){
                    //修改会员统计信息
                    Long memberId = order.getMemberId();
                    CywMemberStatisticsInfo memberStatisticsInfo = memberStatisticsInfoService.selectInfoByMemberId(memberId);
                    memberStatisticsInfo.setConsumeAmount(memberStatisticsInfo.getConsumeAmount().add(order.getPayAmount()));
                    memberStatisticsInfo.setCouponAmount(memberStatisticsInfo.getCouponAmount().add(order.getCouponAmount()));
                    memberStatisticsInfo.setCouponCount(memberStatisticsInfo.getCouponCount() - (order.getCouponHistoryId() == null ? 0 : 1));
                    memberStatisticsInfo.setOrderCount(memberStatisticsInfo.getOrderCount() + 1);
                    Integer integration = order.getIntegration();
                    memberStatisticsInfo.setIntegration(memberStatisticsInfo.getIntegration() + integration);
                    Integer growth = order.getGrowth();
                    memberStatisticsInfo.setGrowth(memberStatisticsInfo.getGrowth() + growth);
                    memberStatisticsInfoService.updateCywMemberStatisticsInfo(memberStatisticsInfo);
                    //商品销量
                    List<CywOrderItem> cywOrderItems = orderItemService.selectListByOrderSn(orderSn);
                    List<Long> skuIds = cywOrderItems.stream().map(CywOrderItem::getSkuId).collect(Collectors.toList());
                    List<CywProSkuInfo> cywProSkuInfos = skuInfoService.selectListBySkuIds(skuIds);
                    cywProSkuInfos.forEach(skuInfo -> {
                        CywOrderItem cywOrderItem = cywOrderItems.stream().filter(item -> item.getSkuId().equals(skuInfo.getSkuId())).findFirst().get();
                        skuInfo.setSaleCount(skuInfo.getSaleCount() + cywOrderItem.getSkuQuantity());
                    });
                    skuInfoService.updateBatch(cywProSkuInfos);
                    // 积分记录
                    Date date = new Date();
                    CywGrowthChangeHistory growthChangeHistory = new CywGrowthChangeHistory();
                    growthChangeHistory.setMemberId(memberId);
                    growthChangeHistory.setCreateTime(date);
                    growthChangeHistory.setChangeCount(growth);
                    growthChangeHistory.setNote("订单号：" + orderSn);
                    growthChangeHistory.setSourceType(1);
                    growthChangeHistoryService.insertCywGrowthChangeHistory(growthChangeHistory);
                    // 成长值记录
                    CywIntegrationChangeHistory integrationChangeHistory = new CywIntegrationChangeHistory();
                    integrationChangeHistory.setMemberId(memberId);
                    integrationChangeHistory.setCreateTime(date);
                    integrationChangeHistory.setChangeCount(integration);
                    integrationChangeHistory.setNote("订单号：" + orderSn);
                    integrationChangeHistory.setSourceType(1);
                    integrationChangeHistoryService.insertCywIntegrationChangeHistory(integrationChangeHistory);

                    //支付成功状态
                    cywOrderMapper.updateOrderStatus(orderSn, OrderStatusEnum.PAYED.getCode());
                }

            }
        }finally {
            lock.unlock();
        }


    }

    @Override
    public List<MonthTurnoverVO>  monthTurnoverSum(Date yearStart, Date yearEnd) {
        return cywOrderMapper.monthTurnoverSum(yearStart, yearEnd);
    }

    @Override
    public BigDecimal totalTurnoverSum(Date todayStart, Date todayEnd) {
        return cywOrderMapper.totalTurnoverSum(todayStart, todayEnd);
    }

    /**
     * 查询订单列表
     *
     * @param cywOrder 订单
     * @return 订单
     */
    @Override
    public List<CywOrder> selectCywOrderList(CywOrder cywOrder) {
        List<CywOrder> list = cywOrderMapper.selectCywOrderList(cywOrder);
        if (CollectionUtil.isNotEmpty(list)){
            buildOrderItems(list);
        }
        return list;
    }

    private void buildOrderItems(List<CywOrder> list) {
        List<String> orderSns = list.stream().map(CywOrder::getOrderSn).collect(Collectors.toList());
        List<CywOrderItem> orderItems = orderItemService.selectListByOrderSns(orderSns);
        list.forEach(order -> {
            order.setItems(orderItems.stream().filter(item -> item.getOrderSn().equals(order.getOrderSn())).collect(Collectors.toList()));
        });
    }

    /**
     * 新增订单
     *
     * @param cywOrder 订单
     * @return 结果
     */
    @Override
    public int insertCywOrder(CywOrder cywOrder) {
        cywOrder.setCreateTime(DateUtils.getNowDate());
        return cywOrderMapper.insertCywOrder(cywOrder);
    }

    /**
     * 修改订单
     *
     * @param cywOrder 订单
     * @return 结果
     */
    @Override
    public int updateCywOrder(CywOrder cywOrder) {
        return cywOrderMapper.updateCywOrder(cywOrder);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteCywOrderByIds(Long[] ids) {
        return cywOrderMapper.deleteCywOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteCywOrderById(Long id) {
        return cywOrderMapper.deleteCywOrderById(id);
    }

    @Override
    public CywOrder selectOrderByOrderSn(String orderSn) {
        return cywOrderMapper.selectOrderByOrderSn(orderSn);
    }

    @Override
    public int updateOrderStatus(String orderSn, Integer status) {
        return cywOrderMapper.updateOrderStatus(orderSn, status);
    }


}
